package com.fzrskj.cloud.free.sys.utils;

import com.fzrskj.cloud.free.core.utils.EncryptUtils;
import com.fzrskj.cloud.free.miniservice.enums.MiniServiceStatus;
import com.fzrskj.cloud.free.miniservice.utils.MiniServiceRequest;
import com.fzrskj.cloud.free.sys.bean.SysMiniServiceBean;
import com.google.common.base.Splitter;
import ms.core.tool.StrTool;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 微服务访问验证.
 * Created by sofical on 2020/9/28.
 */
public class MiniServerApiCheckUtils {
    /**
     * 验证是否为微服务的请求.
     * @param request 请求句柄.
     * @return 判断结果.
     */
    public static Boolean check(HttpServletRequest request) {
        // 获取认证参数
        String authorize = request.getHeader("auth");
        if (StrTool.isBlankStr(authorize)) {
            return false;
        }
        Map<String, String> params = Splitter.on(";").withKeyValueSeparator("=").split(authorize);
        if (!params.containsKey("id") || !params.containsKey("nonce") || !params.containsKey("sn")) {
            return false;
        }
        String id = params.get("id");
        String nonce = params.get("nonce");
        String sn = params.get("sn");
        if (StrTool.isBlankStr(id) || StrTool.isBlankStr(nonce) || StrTool.isBlankStr(sn)) {
            return false;
        }
        id = id.trim();
        nonce = nonce.trim();
        sn = sn.trim();

        // 获取微服务
        SysMiniServiceUtils miniServiceUtils = new SysMiniServiceUtils();
        SysMiniServiceBean miniServiceBean = miniServiceUtils.getByCode(id);
        if (null == miniServiceBean || MiniServiceStatus.STOP.equals(miniServiceBean.getStatus())) {
            return false;
        }
        String secretKey = EncryptUtils.decodeSave(miniServiceBean.getServiceApiSecretKey());

        // 校验
        String host = request.getRemoteHost();
        String method = request.getMethod();
        String apiName = request.getParameter("fn");

        String mySn = MiniServiceRequest.buildAuth(host, method, apiName, secretKey, nonce);
        return sn.equals(mySn);
    }
}
